package com.reebake.ideal.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.reebake.ideal.message.entity.MessageNotification;
import com.reebake.ideal.message.mapper.MessageNotificationMapper;
import com.reebake.ideal.message.service.MessageNotificationPlusService;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

@Service
@RequiredArgsConstructor
public class MessageNotificationPlusServiceImpl implements MessageNotificationPlusService {
    private final MessageNotificationMapper messageNotificationMapper;

    @Override
    public List<MessageNotification> latest(String userId, int pageSize) {
        LambdaQueryWrapper<MessageNotification> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MessageNotification::getReceiverId, userId)
                .orderByDesc(MessageNotification::getSendTime)
                ;

        Page<MessageNotification> page = new Page<>(1, pageSize);
        return messageNotificationMapper.selectPage(page, queryWrapper).getRecords();
    }

    @Override
    public void markAll(String userId) {
        LambdaUpdateWrapper<MessageNotification> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(MessageNotification::getIsRead, true)
                .eq(MessageNotification::getReceiverId, userId)
                .eq(MessageNotification::getIsRead, false);

        messageNotificationMapper.update(updateWrapper);
    }

    @Override
    public void markByIds(Collection<String> messageNotificationIds) {
        LambdaUpdateWrapper<MessageNotification> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(MessageNotification::getIsRead, true)
                .in(MessageNotification::getMessageNotificationId, messageNotificationIds)
                .eq(MessageNotification::getIsRead, false);

        messageNotificationMapper.update(updateWrapper);
    }

    @Override
    public void clear(String userId) {
        LambdaQueryWrapper<MessageNotification> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MessageNotification::getReceiverId, userId);
        messageNotificationMapper.delete(queryWrapper);
    }
}
